﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Atmk.WaterMeter.MIS.Base;
using Atmk.WaterMeter.MIS.Common;
using Atmk.WaterMeter.MIS.Commons;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.Statistics;
using Atmk.WaterMeter.MIS.Commons.Utils;
using Atmk.WaterMeter.MIS.Commons.ViewModels;
using Atmk.WaterMeter.MIS.Commons.ViewModels.OwnerMeter;
using Atmk.WaterMeter.MIS.Datas;
using Atmk.WaterMeter.MIS.Entities;
using Atmk.WaterMeter.MIS.Entities.Enums;
using Atmk.WaterMeter.MIS.Entities.Models;
using Atmk.WaterMeter.MIS.Models.ModelPuls;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NLog;

namespace Atmk.WaterMeter.MIS.Controllers
{
    [Authorize]
    public class MeterController : BaseApiController
    {
        protected Logger _logger = LogManager.GetCurrentClassLogger();
        private readonly TokenHelper _tokenHelper;
        private readonly IMeterLogic _meterLogic;

        /// <inheritdoc />
        public MeterController(
            IMeterLogic meterLogic,
            TokenHelper tokenHelper)
        {
            _meterLogic = meterLogic;
            _tokenHelper = tokenHelper;
        }

        /// <summary>
        /// 获取水表类型
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddMeter([FromBody] dynamic obj)
        {
            try
            {
                var token = _tokenHelper.GetTokenByHttpContext();
                if (obj == null)
                {
                    _logger.Debug("传入Josn数据为空");
                    return Ok(new { errcode = 1, msg = $"传入数据出错" });
                }
                var result = _meterLogic.InsertMeter(obj.districtId.ToString(), obj.owner, obj.waterMeter, token, out string ErrorMessage);

                return Ok(result
                ? new { errcode = 0, msg = "ok" }
                : new { errcode = 1, msg = ErrorMessage });
            }
            catch (Exception e)
            {
                _logger.Error(e.Message);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"添加信息失败"
                });
            }
        }

        //批量添加水表
        [HttpPost]
        public IActionResult UploadFile([FromForm] IFormCollection formCollection)
        {
            try
            {
                Token token = _tokenHelper.GetTokenByHttpContext();
                string districtId = formCollection["districtid"].ToString();
                StreamReader reader = new StreamReader(formCollection.Files[0].OpenReadStream(), Encoding.GetEncoding("GBK"));
                //String content = reader.ReadToEnd();
                StringBuilder sb = new StringBuilder();
                string strline = "";
                while ((strline = reader.ReadLine()) != null)
                {
                    string[] arr = strline.Split(',');
                    try
                    {
                        using (var _context = ContextBuilder.Build())
                        {
                            if (string.IsNullOrWhiteSpace(arr[0]))
                            {
                                sb.Append(arr[2] + "缺少业主姓名 <br>");
                                continue;
                            }
                            Owner ownerEntity = new Owner()
                            {
                                DistrictId = districtId,
                                Name = arr[0],
                                HouseNumber = arr[1],
                                Memo=""
                            };
                            _context.Owner.Add(ownerEntity);

                            var obj = new OwnerMeterEntity();
                            obj.owner.ownerId = ownerEntity.Id;
                            obj.waterMeter.meterType = "冷水水表";
                            obj.waterMeter.meterNumber = arr[2];
                            obj.waterMeter.refillType = "后付费";
                            obj.waterMeter.priceId = formCollection["priceId"].ToString();
                            obj.waterMeter.commType = string.Empty;
                            obj.waterMeter.imei = arr[3];
                            obj.waterMeter.meterDatas.collector = arr[3];
                            obj.waterMeter.meterBottomNumber = arr[4];
                            bool r = _meterLogic.InsertMeter(districtId, obj.owner, obj.waterMeter, token, out string ErrorMessage);
                            if (r == false)
                            {
                                sb.Append(arr[2] + "<br>");
                                continue;
                            }
                            var result_count = _context.SaveChanges();
                        }
                    }
                    catch (Exception ex)
                    {
                        sb.Append(arr[2] + "新增业主时失败！" + ex.ToString() + " <br>");
                        continue;
                    }
                    System.Threading.Thread.Sleep(1500);
                }
                return Ok(sb.ToString());
            }
            catch (Exception ex)
            {
                _logger.Debug("批量新增catch：" + ex.Message);
                return Ok("导入失败：" + ex.Message);
            }
        }
    }
}